package com.itobase.statusDetect.Service.impl;

import com.itobase.statusDetect.Model.Organization;
import com.itobase.statusDetect.Repository.OrganizationRepository;
import com.itobase.statusDetect.Service.OrganizationService;
import com.itobase.statusDetect.Util.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.InvalidParameterException;

/**
 * @author htyu
 * @date 2019/2/24
 */
@Service
public class OrganizationServiceImpl implements OrganizationService {

    @Autowired
    OrganizationRepository organizationRepository;

    @Override
    public Organization create(String fatherID,String name){
        Organization organization = new Organization();
        if(fatherID == null){
            organization.setFowardID("");
        }else{
            Organization organization_father = organizationRepository.findById(fatherID).orElseThrow(() -> new RuntimeException("上一级组织不存在"));
            organization.setFowardID(fatherID);
        }
        checkExist(name);
        organization.setName(name);
        return organizationRepository.save(organization);
    }

    @Override
    public Organization rename(String id,String name){
        Organization organization = organizationRepository.findById(id).orElseThrow(()-> new RuntimeException("参数错误"));
        checkExist(name);
        organization.setName(name);
        return organizationRepository.save(organization);
    }

    public void checkExist(String name) {
        Organization organization = organizationRepository.findByName(name);
        if (organization!=null)
            throw new InvalidParameterException("组织名重复,请勿重复添加");
    }

}
